import axios from "axios";
import {useUserInfoStore} from "@/store/index";

// 初始化axios实例
const instance = axios.create({
    baseURL: "http://localhost:8082/api/",
    timeout: 10000
})

// 将token信息添加的请求头中
export const $setToken = () => {
    if (useUserInfoStore.token) {
        instance.defaults.headers.common['Token'] = useUserInfoStore.token
    }

}

/**
 * GET方法
 * @param url 请求地址
 * @param params 参数对象
 * @returns {any}
 */
export const $get = async (url, params) => {
    $setToken()

    const {data} = await instance.get(url, {
        params
    })
    return data
}

/**
 * POST方法
 * @param url 请求地址
 * @param params 参数对象
 * @returns {any}
 */
export const $post = async (url, params) => {
    $setToken()

    let {data} = await instance.post(url, params)
    return data
}

/**
 * PUT方法
 * @param url 请求地址
 * @param params 参数对象
 * @returns {any}
 */
export const $put = async (url, params) => {
    $setToken()

    let {data} = await instance.put(url, params)
    return data
}

/**
 * DELETE方法
 * @param url 请求地址
 * @param params 参数对象
 * @returns {Promise<any>}
 */
export const $delete = async (url, params) => {
    $setToken()

    let {data} = await instance.delete(url, {
        params
    })
    return data
}